/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package chelydra.sharelydra.client.network;

import chelydra.sharelydra.client.Core;
import chelydra.sharelydra.client.database.DatabaseManager;
import chelydra.sharelydra.client.file.FileManager;
import chelydra.sharelydra.client.friend.Notification;
import chelydra.sharelydra.client.message.DownloadPart;
import chelydra.sharelydra.client.message.GetFileList;
import chelydra.sharelydra.client.message.Message;
import chelydra.sharelydra.client.message.SendFileList;
import chelydra.sharelydra.client.message.UploadPart;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Benjamin
 */
public class Reciever extends Thread {

    public Socket s;
    public int port;
    public BufferedReader in;
    public OutputStreamWriter osw;


public Reciever(Socket s) throws IOException{
        this.s=s;
				System.out.println("Receiver created");


    }

	@Override
	public void run(){

		try {
			while (this.s.isConnected()) {
				System.out.println("BufferedReader created");
				in = new BufferedReader(new InputStreamReader(this.s.getInputStream()));
				String tempString;
				while(!s.isClosed()){
					System.out.println("Socket non closed");
					while ( in.ready() == false) {
							}
					tempString = in.readLine();
					System.out.println("Message Received");
					System.out.println(tempString);
					this.processMessage(tempString);

				}
			}
		} catch (IOException ex) {
				Logger.getLogger(Reciever.class.getName()).log(Level.SEVERE, null, ex);
		}
	}


//Functions below will be completed when the other classes will be implemented
public void processMessage(String tempString) throws IOException{
    Message mes = new Message();
    mes.fromString(tempString);
    this.osw = new OutputStreamWriter(this.s.getOutputStream());

    if(mes.getType() == 1){
        //GetFileList mesgfl = new GetFileList();
        //mesgfl.fromString(tempString);
        //this.processGetFileList(mesgfl);
				this.processGetFileList(mes);


    }else if(mes.getType() == 2){
        SendFileList messfl = new SendFileList();
        messfl.fromString(tempString);
        this.processSendFileList(messfl);


    }else if(mes.getType() == 3){
        DownloadPart mesdp = new DownloadPart();
        mesdp.fromString(tempString);
        this.processDownloadPart(mesdp);

        
    }else if(mes.getType() == 4){
        UploadPart mesup = new UploadPart();
        mesup.fromString(tempString);
        this.processUploadPart(mesup);
    }
}

public void processGetFileList(Message mes) throws IOException{
    //A compléter et remplacer par la suite par la string au format XML
    DatabaseManager dm = Core.getApplication().getDatabaseManager();
    Collection<Map<String,String>> temp = dm.getFileList();
    StringBuffer xml = new StringBuffer("");
 
    System.out.println("Number file to send Size : "+ temp.size());

		Iterator i = temp.iterator();
		while (i.hasNext()) {
			Map<String,String> file = (Map<String,String>)i.next();
			xml.append("<file><fileID>"+file.get("FileID")+"</fileID>" +
							"<fileName>"+file.get("FileName")+"</fileName>" +
							"<filePath>"+file.get("FilePath")+"</filePath>" +
							"<fileSize>"+file.get("FileSize")+"</fileSize></file>");
		}

    SendFileList reply = new SendFileList(xml.toString());
    this.osw.write(reply.toString(),0,reply.toString().length());
    this.osw.flush();
		//this.osw.close();
    DatabaseManager dbm = Core.getApplication().getDatabaseManager();
		String nickname = Core.getApplication().getFriendManager().getNicknameForIp(s.getInetAddress().getHostAddress());
    Notification newNote = new Notification(Notification.LIST_FILE_SENT,nickname);
    dbm.addNewNotification(newNote);
    Core.getApplication().getView().updateNotifications();
}

public void processSendFileList(SendFileList mes){


}

public void processDownloadPart(DownloadPart mes) throws IOException{
    DatabaseManager dm = Core.getApplication().getDatabaseManager();
    Vector<Map> temp = (Vector) dm.getFileInfoById(mes.getFileId());
    System.out.println(temp);
    String fileSize = "";
    if(temp.size()!=0){
        String fileName = (String) temp.elementAt(0).get("FileName");
        String filePath = (String) temp.elementAt(0).get("FilePath");
        fileSize = (String) temp.elementAt(0).get("FileSize");
        byte[] slice = FileManager.sliceReader(filePath+"/"+fileName, mes.getStartByte(), mes.getFinishByte()-mes.getStartByte()+1);
        String toSend = ByteConvertor.toString(slice);
        int intfileSize = 0;
        intfileSize = Integer.parseInt(fileSize);
        float progress = ((float) mes.getFinishByte() / (float) intfileSize)*100;
        Core.getApplication().getView().updateUploadTable(fileName,Float.toString(progress));
        UploadPart reply=new UploadPart();
        reply.setVersion(1);
        reply.setType(4);
        reply.setStatus(1);
        reply.setFileId(mes.getFileId());
        reply.setFileData(toSend);
        System.out.println("Receiver will send a message of type "+reply.getType());
        this.osw.write(reply.toString(),0,reply.toString().length());
        this.osw.flush();
				//this.osw.close();
    }else{
        UploadPart reply=new UploadPart();
        reply.setStatus(0);
        reply.setFileId(mes.getFileId());
        this.osw.write(reply.toString(),0,reply.toString().length());
        this.osw.flush();
				//this.osw.close();
    }

}

public void processUploadPart(UploadPart mes){


    

}


}
